package com.yuecai.base;


import org.hibernate.Session;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.query.NativeQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * Created by fmtq on 2017/10/29.
 */
@SuppressWarnings("ALL")
@Repository
@Primary
public  class BaseRepositoryImpl {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private EntityManager entityManager;




    public Boolean  jdbcBatchInsert(List<Map<String,Object>> list,String tableName){
        if (list==null||list.size()==0){
            return false;
        }
        Map<String,Object> firstMap = list.get(0);
        String sql = "insert into "+ tableName;
        StringBuffer fiels = new StringBuffer( " ( " );
        StringBuffer values = new StringBuffer( " ( " );
        Integer f = 0;
        for (String key:firstMap.keySet()){
            f++;
            if (f==firstMap.size()){
                fiels.append(""+key+")");
                values.append("?)");
            }else {
                fiels.append(""+key+",");
                values.append("?,");

            }
        }
        sql = sql +fiels.toString()+"values"+values.toString();
        try {
            int[] updatedCountArray=jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
                    Map<String,Object> map = list.get(i);
                    Integer j = 1;
                    for (String key:map.keySet()){
                        preparedStatement.setObject(j,map.get(key));
                        j++;
                    }
                }
                @Override
                public int getBatchSize() {
                    return list.size();
                }
            });
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public Boolean  jdbcBatchUpdate(List<Map<String,Object>> list,String tableName){
        if (list==null||list.size()==0){
            return false;
        }
        Map<String,Object> firstMap = list.get(0);
        String sql = "update "+ tableName;
        StringBuffer fiels = new StringBuffer( " set " );
        StringBuffer where = new StringBuffer( " where 1 = 1 " );
        Integer f = 0;
        for (String key:firstMap.keySet()){
            f++;
            if (key.contains("sqlWhere_")){
                key = key.replace("sqlWhere_","");
                where.append(" and  "+key+"=? ");
            }else {
                fiels.append(" " +key+ "=? ,");
            }
        }
        fiels.deleteCharAt(fiels.length()-1);
        sql = sql +fiels.toString()+" "+where.toString();
        try {
            int[] updatedCountArray=jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
                    Map<String,Object> map = list.get(i);
                    Integer j = 1;
                    for (String key:map.keySet()){
                        preparedStatement.setObject(j,map.get(key));
                        j++;
                    }
                }
                @Override
                public int getBatchSize() {
                    return list.size();
                }
            });
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public Boolean  jdbcBatch(List<Map<String,Object>> list,String sql){
        if (list==null||list.size()==0){
            return false;
        }
        try {
            int[] updatedCountArray=jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
                    Map<String,Object> map = list.get(i);
                    Integer j = 1;
                    for (String key:map.keySet()){
                        preparedStatement.setObject(j,map.get(key));
                        j++;
                    }
                }
                @Override
                public int getBatchSize() {
                    return list.size();
                }
            });
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }




    public List<Map> getAllBySql(String datasql){
        Session session = entityManager.unwrap(Session.class);
        NativeQuery sqlQuery = session.createNativeQuery(datasql);
        List<Map> list = sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP).list();
        return list;
    }
    public List<Map<String,String>> getAllBySqlMapString(String datasql){
        Session session = entityManager.unwrap(Session.class);
        NativeQuery sqlQuery = session.createNativeQuery(datasql);
        List<Map<String,String>> list = sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP).list();
        return list;
    }
    public Map getMapBySql(String datasql){
        Session session = entityManager.unwrap(Session.class);
        NativeQuery sqlQuery = session.createNativeQuery(datasql);
        List<Map> list = sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP).list();
        if (list==null||list.size()==0){
            return null;
        }
        return list.get(0);
    }
    public Map<String,String> getMapBySqlString(String datasql){
        Session session = entityManager.unwrap(Session.class);
        NativeQuery sqlQuery = session.createNativeQuery(datasql);
        List<Map<String,String>> list = sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP).list();
        if (list==null||list.size()==0){
            return null;
        }
        return list.get(0);
    }
}
